package com.yuncheng.spcyApi.flowController;

import com.yuncheng.vo.CurrentUserVo;
import com.yuncheng.vo.HttpResult;
import org.apache.commons.collections.CollectionUtils;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.yuncheng.spcyApi.alog.annotation.Log;
import com.yuncheng.common.base.controller.BaseController;
import com.yuncheng.spcyApi.constant.common.BusinessConstant;
import com.yuncheng.spcyApi.constant.common.SpcyConstant;
import com.yuncheng.spcyApi.constant.flow.YbjcyFlowConstant;
import com.yuncheng.spcyApi.entity.SpcyKpYbjcy;
import com.yuncheng.spcyApi.flow.FlowVo;
import com.yuncheng.spcyApi.flow.JcyYbkpFlowService;
import com.yuncheng.spcyApi.flow.SpcyFlowConstant;
import com.yuncheng.spcyApi.mapper.SpcyKpYbjcyMapper;
import com.yuncheng.spcyApi.service.ISpcyKpYbjcyService;
import com.yuncheng.spcyApi.utils.*;
import com.yuncheng.spcyApi.vo.common.OrderItemVo;
import com.yuncheng.spcyApi.vo.common.PageVo;
import com.yuncheng.spcyApi.vo.flow.YbjcyFlowVo;
import com.yuncheng.spcyApi.vo.spcy.SpcyReturnVo;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiImplicitParam;
import io.swagger.annotations.ApiImplicitParams;
import io.swagger.annotations.ApiOperation;
import org.apache.commons.lang3.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import org.springframework.web.bind.annotation.*;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletResponse;
import java.io.OutputStream;
import java.net.URLEncoder;
import java.util.*;

@Api(tags = "审评查验-见习考评流程接口")
@RestController
@RequestMapping("/api/spzx-spcy/flow-ybjcy")
public class JcyYbkpFlowController extends BaseController<SpcyKpYbjcy, ISpcyKpYbjcyService> {
    private static final Logger log = LoggerFactory.getLogger(JcyYbkpFlowController.class);

    @Resource
    private SpcyKpYbjcyMapper spcyKpYbjcyMapper;

    @Resource
    private ISpcyKpYbjcyService spcyKpYbjcyService;

    /*@Resource
    private YbjcyFlowConstant ybjcyFlowConstant;

    @Resource
    private YbjcyFlowService ybjcyFlowService;*/

    @Resource
    private MyExcelUtils myExcelUtils;

    @Resource
    private JcyYbkpFlowService jcyYbkpFlowService;


//    @Log(title = "见习考评-流程监控-分页查询")
//    @ApiOperation(value = "见习考评-流程监控-分页查询")
    @GetMapping("flowJkPage")
    public HttpResult<?> flowJkPage(YbjcyFlowVo flowVo, PageVo pageVo, OrderItemVo orderItemVo,
                                    @RequestParam(name = "onlyCurrentUser", defaultValue = "false") boolean onlyCurrentUser){

        flowVo.setFblzt(SpcyConstant.BLZT_DB);
//        flowVo.setFlcmc(SpcyFlowConstant.YBKP_LCMC);
        Page<YbjcyFlowVo> page = new Page<>(pageVo.getPageNo(), pageVo.getPageSize());
        String userid = null;
        if (onlyCurrentUser){
            CurrentUserVo user = GetCurrentUserUtils.getCurrentUser();
            if (user == null){
                return HttpResult.error("请重新登录，Token已失效！");
            }
            userid = user.getId();
        }
        IPage<YbjcyFlowVo> list = spcyKpYbjcyMapper.selectFlowJobPage(page, userid, flowVo, orderItemVo);

        return HttpResult.ok(list);
    }


    @Log(title = "见习考评-流程列表-分页查询")
    @ApiOperation(value = "见习考评-流程列表-分页查询")
    @GetMapping("flowJobPage")
    public HttpResult<?> flowJobPage(YbjcyFlowVo flowVo, PageVo pageVo, OrderItemVo orderItemVo){

        flowVo.setFblzt(SpcyConstant.BLZT_DB);
//        flowVo.setFlcmc(SpcyFlowConstant.YBKP_LCMC);
        Page<YbjcyFlowVo> page = new Page<>(pageVo.getPageNo(), pageVo.getPageSize());
        String userid = GetCurrentUserUtils.getCurrentUserId();
        IPage<YbjcyFlowVo> list = spcyKpYbjcyMapper.selectFlowJobPage(page, userid, flowVo, orderItemVo);

        return HttpResult.ok(list);
    }

    @Log(title = "APP见习考评-流程列表-分页查询")
    @ApiOperation(value = "APP见习考评-流程列表-分页查询")
    @GetMapping("flowAppJobPage")
    public HttpResult<?> flowAppJobPage(YbjcyFlowVo flowVo, PageVo pageVo, OrderItemVo orderItemVo){

        flowVo.setFblzt(SpcyConstant.BLZT_DB);
        flowVo.setPchj(SpcyFlowConstant.YBKP_HJMC_JBRSH);
        IPage<YbjcyFlowVo> list = spcyKpYbjcyMapper.selectFlowJobPage(
                new Page<>(pageVo.getPageNo(),
                pageVo.getPageSize()),
                GetCurrentUserUtils.getCurrentUserId(),
                flowVo,
                orderItemVo);

        return HttpResult.ok(list);
    }


    @Log(title = "见习考评-我的已办流程列表-分页查询")
    @ApiOperation(value = "见习考评-我的已办流程列表-分页查询")
    @GetMapping("flowMyYbJobPage")
    public HttpResult<?> flowMyYbJobPage(YbjcyFlowVo flowVo, PageVo pageVo, OrderItemVo orderItemVo){

        flowVo.setFblzt(SpcyConstant.BLZT_YB);
        flowVo.setFlcmc(SpcyFlowConstant.YBKP_LCMC);
        Page<YbjcyFlowVo> page = new Page<>(pageVo.getPageNo(), pageVo.getPageSize());
        String userid = GetCurrentUserUtils.getCurrentUserId();
        IPage<YbjcyFlowVo> list = spcyKpYbjcyMapper.selectYbFlowJobPage(page, userid, flowVo, orderItemVo);

        /*if (CollectionUtil.isNotEmpty(list.getRecords())){
            list.setRecords(list.getRecords().stream().collect(Collectors.collectingAndThen(
                    Collectors.toCollection(
                            () -> new TreeSet<>(
                                    Comparator.comparing(o -> o.getYbid())
                            )
                    ), ArrayList<YbjcyFlowVo>::new
            )));
//            list.setTotal(list.getRecords().size());
        }*/
        return HttpResult.ok(list);
    }

    @Log(title = "见习考评查询")
    @ApiOperation(value = "见习考评查询")
    @GetMapping("jxkpcxPageList")
    public HttpResult<?> jxkpcxPageList(YbjcyFlowVo flowVo, PageVo pageVo, OrderItemVo orderItemVo){

        flowVo.setFlcmc(SpcyFlowConstant.YBKP_LCMC);
        Page<YbjcyFlowVo> page = new Page<>(pageVo.getPageNo(), pageVo.getPageSize());
        IPage<YbjcyFlowVo> list = spcyKpYbjcyMapper.selectJxkpcxPageList(page, null, flowVo, orderItemVo);

        return HttpResult.ok(list);
    }

    @Log(title = "见习考评-保存接口")
    @ApiOperation(value = "见习考评-保存接口")
    @PostMapping(value = "/saveFlow")
    public HttpResult<?> saveFlow(@RequestBody FlowVo flowVo) {

        jcyYbkpFlowService.handleFlow(flowVo,flowVo.getJobid(),null,SpcyFlowConstant.SUBMIT_TYPE_SAVE,flowVo.getOpinion());

        return HttpResult.ok("保存成功");
    }

    @Log(title = "见习考评-提交接口")
    @ApiOperation(value = "见习考评-提交接口")
    @PostMapping(value = "/submitFlow")
    public HttpResult<?> submitFlow(@RequestBody FlowVo flowVo) {

        jcyYbkpFlowService.handleFlow(flowVo,flowVo.getJobid(),null,SpcyFlowConstant.SUBMIT_TYPE_SUBMIT,flowVo.getOpinion());

        return HttpResult.ok("提交成功");
    }

    @Log(title = "退回上一环节流程任务")
    @ApiOperation(value = "退回上一环节流程任务")
    @ApiImplicitParams(value = {
            @ApiImplicitParam(name = "jobid",value = "流程任务id",required = true),
            @ApiImplicitParam(name = "opinion",value = "意见",required = true)
    })
    @PostMapping(value = "returnUpperFlowJob")
    public HttpResult<?> returnUpperFlowJob(@RequestBody SpcyReturnVo spcyReturnVo){

        jcyYbkpFlowService.getReturnUpperFlowJob(spcyReturnVo);
        return HttpResult.ok("退回成功");
    }

    @Log(title = "见习考评查询当前流程任务详情-通过当前流程任务id")
    @ApiOperation(value = "见习考评-查询当前流程任务详情-通过当前流程任务id")
    @GetMapping(value = "queryJobByJobId")
    public HttpResult<?> queryJobByJobId(@RequestParam(value = "jobid",defaultValue = "")String jobid){
        if (StringUtils.isBlank(jobid)){
            return HttpResult.error("流程任务参数为空！");
        }

        return HttpResult.ok(jcyYbkpFlowService.getJobConcernByJobId(jobid));
    }

    @Log(title = "获取APP-见习考评查询当前流程任务详情")
    @ApiOperation(value = "获取APP-见习考评-查询当前流程任务详情")
    @GetMapping(value = "queryAppJobInfo")
    public HttpResult<?> queryAppJobInfo(@RequestParam(value = "jobid",defaultValue = "")String jobid){
        if (StringUtils.isBlank(jobid)){
            return HttpResult.error("流程任务参数为空！");
        }

        return HttpResult.ok(jcyYbkpFlowService.getAppJobConcernByJobId(jobid));
    }

    @Log(title = "批量查询预备检查员考评信息")
    @ApiOperation(value = "批量查询预备检查员考评信息")
    @ApiImplicitParam(name = "ids",value = "预备检查员信息id,id参数逗号拼接")
    @GetMapping(value = "queryBatchYbjcyList")
    public HttpResult<?> queryBatchYbjcyList(@RequestParam(value = "ids",defaultValue = "")String ids){
        if (StringUtils.isBlank(ids)){
            return HttpResult.error("参数不能为空,请选择数据");
        }
        List<String> idsList = StringPatternUtils.getListByIds(ids);
        List<SpcyKpYbjcy> ybjcyList = new ArrayList<>();
        if (CollectionUtils.isNotEmpty(idsList)){
            ybjcyList = spcyKpYbjcyService.listByIds(idsList);
        }
        return HttpResult.ok(ybjcyList);
    }

    @Log(title = "预备检查考评统计")
    @ApiOperation(value = "预备检查考评统计")
    @GetMapping(value = "queryYbjcyTjPageList")
    public HttpResult<?> queryYbjcyTjPageList(SpcyKpYbjcy ybjcy, PageVo pageVo, OrderItemVo orderItemVo){
        Page<SpcyKpYbjcy> page = new Page<>(pageVo.getPageNo(),pageVo.getPageSize());
        LambdaQueryWrapper<SpcyKpYbjcy> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.like(StringUtils.isNotBlank(ybjcy.getFjcyxm()),SpcyKpYbjcy::getFjcyxm,ybjcy.getFjcyxm());
        queryWrapper.like(StringUtils.isNotBlank(ybjcy.getFgzdw()),SpcyKpYbjcy::getFgzdw,ybjcy.getFgzdw());
        queryWrapper.like(StringUtils.isNotBlank(ybjcy.getFjclx()),SpcyKpYbjcy::getFjclx,ybjcy.getFjclx());
        queryWrapper.like(StringUtils.isNotBlank(ybjcy.getFqymc()),SpcyKpYbjcy::getFqymc,ybjcy.getFqymc());
        queryWrapper.like(StringUtils.isNotBlank(ybjcy.getFzzxm()),SpcyKpYbjcy::getFzzxm,ybjcy.getFzzxm());
        queryWrapper.like(StringUtils.isNotBlank(ybjcy.getFpj()),SpcyKpYbjcy::getFpj,ybjcy.getFpj());
        queryWrapper.eq(SpcyKpYbjcy::getFlczt,SpcyFlowConstant.LCZT_LCBJ);

        if (StringUtils.isNotBlank(orderItemVo.getOrderItem())){
            OrderItemUtils.setOrderItem(queryWrapper,orderItemVo);
        }
        Page<SpcyKpYbjcy> page1 = spcyKpYbjcyService.page(page, queryWrapper);

        return HttpResult.ok(page1);
    }

    @Log(title = "导出统计基本信息数据-表格excel")
    @ApiOperation(value = "导出统计基本信息数据-表格excel")
    @GetMapping("/exportRckpYbJbxxData")
    public void exportRckpYbJbxxData(@RequestParam(value = "ids",defaultValue = "")String ids,
                                     SpcyKpYbjcy ybjcy,
                                     OrderItemVo orderItemVo,
                                     HttpServletResponse response){
        try {
            String name = "exportRckpYbJbxxData";
            response.setContentType("application/ms-excel;charset=UTF-8");
            response.setHeader("Content-Disposition", "attachment;filename="
                    .concat(String.valueOf(URLEncoder.encode(name+".xls", "UTF-8"))));
            OutputStream out = response.getOutputStream();

            List<String> IdsList = StringPatternUtils.getListByIds(ids);
            List<Object> list = new ArrayList<>(); // 导出的数据
            // 多选导出
            if (StringUtils.isNotEmpty(ids)) {
                List<SpcyKpYbjcy> ybjcyList = spcyKpYbjcyService.listByIds(IdsList);
                if (CollectionUtils.isNotEmpty(ybjcyList)){
                    for (SpcyKpYbjcy e : ybjcyList){
                        list.add(e);
                    }
                }
            }else {
                LambdaQueryWrapper<SpcyKpYbjcy> queryWrapper = new LambdaQueryWrapper<>();
                queryWrapper.like(StringUtils.isNotBlank(ybjcy.getFjcyxm()),SpcyKpYbjcy::getFjcyxm,ybjcy.getFjcyxm());
                queryWrapper.like(StringUtils.isNotBlank(ybjcy.getFgzdw()),SpcyKpYbjcy::getFgzdw,ybjcy.getFgzdw());
                queryWrapper.like(StringUtils.isNotBlank(ybjcy.getFjclx()),SpcyKpYbjcy::getFjclx,ybjcy.getFjclx());
                queryWrapper.like(StringUtils.isNotBlank(ybjcy.getFqymc()),SpcyKpYbjcy::getFqymc,ybjcy.getFqymc());
                queryWrapper.like(StringUtils.isNotBlank(ybjcy.getFzzxm()),SpcyKpYbjcy::getFzzxm,ybjcy.getFzzxm());
                queryWrapper.like(StringUtils.isNotBlank(ybjcy.getFpj()),SpcyKpYbjcy::getFpj,ybjcy.getFpj());
                queryWrapper.eq(SpcyKpYbjcy::getFlczt,YbjcyFlowConstant.HJMC_LCJS);
                if (StringUtils.isNotBlank(orderItemVo.getOrderItem())){
                    OrderItemUtils.setOrderItem(queryWrapper,orderItemVo);
                }
                List<SpcyKpYbjcy> ybjcyList = spcyKpYbjcyService.list(queryWrapper);
                // 条件导出
                if (CollectionUtils.isNotEmpty(ybjcyList)){
                    for (SpcyKpYbjcy e : ybjcyList){
                        list.add(e);
                    }
                }
            }
            myExcelUtils.outputListToExclFile(BusinessConstant.IMPORT_RCKP_YBJCY_TJ_XML,list,out); // 导出模板数据成excel
        } catch (Exception e) {
            log.error("导出导出统计基本信息数据出错-{}",e.getMessage());
        }
    }
}
